<template>
	<div v-loading="loading" id="container"></div>
</template>

<script>
	import AMapLoader from '@amap/amap-jsapi-loader'
	import { securityJsCode, key } from './mapConfig'
	//import MapIcon from '@/assets/map-icon.png'
  import MapBlue from "@/assets/map-blue.png";
  import MapGreen from "@/assets/map-green.png";
  import MapRed from "@/assets/map-red.png";
	
	window._AMapSecurityConfig = { securityJsCode }
	let AMap = null

	export default {
    props: {
      defMarker: {
        type: Array,
        default: () => []
      },
      icon: {
        type: String,
        default: '2'
      }
    },
		data() {
			return {
				loading: false,
				map: null,
				lnglat: [],
				adr: {},
				markerList: []
			}
		},
    watch: {
			icon(val) {
				console.log("icon",val)
				if (val) { 
					this.setMarker(this.lnglat)
				}
      }
    },
		mounted() {
			this.initMap()
		},
		methods: {
			async initMap() {
				try {
					this.loading = true

					AMap = await AMapLoader.load({
						key,
						version: '2.0',
						plugins: []
					})

					this.map = new AMap.Map('container', {
            resizeEnable: true,
            layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()]
          })

					this.map.on('click', this.clickMapHandler)
				} catch (error) {
					console.log('error,,,', error)
				} finally {
					this.loading = false
				}
			},

			// 点击
			clickMapHandler(e) {
        this.setMarker([e.lnglat.lng, e.lnglat.lat])
				this.getAddress()
			},

			// 标记
			marker() {
				this.map.remove(this.markerList)
        const iconMap = {
          '2': new AMap.Icon({
            size: new AMap.Size(24, 24),
            imageSize: new AMap.Size(24, 24),
            image: MapBlue
          }),
          '3': new AMap.Icon({
            size: new AMap.Size(24, 24),
            imageSize: new AMap.Size(24, 24),
            image: MapGreen
          }),
          '1': new AMap.Icon({
            size: new AMap.Size(24, 24),
            imageSize: new AMap.Size(24, 24),
            image: MapRed
          })
        }
				const marker = new AMap.Marker({
					map: this.map,
					zIndex: 9999999,
					icon: iconMap[this.icon !== 'null' ? this.icon : '2'],
					offset: new AMap.Pixel(-13, -24),
					position: this.lnglat
				})
				this.markerList = [marker]
			},

      setMarker(lnglat) {
        this.lnglat = lnglat
        this.marker()
        this.map.setCenter(lnglat)
      },

      setCenterByLocation(address) {
        this.map.plugin('AMap.Geocoder', () => {
          const geocoder = new AMap.Geocoder({
            radius: 100,
            extensions: 'all'
          })

          geocoder.getLocation(address, (status, res) => {
            if (status === 'complete' && res.info === 'OK') {
              let location = res.geocodes[res.geocodes.length - 1].location
              this.map.setCenter([location.lng, location.lat])
            } else {
              console.log('fail,,,', status, res)
            }
          })
        })
      },

			// 经纬度转化为详细地址
			getAddress() {
				this.map.plugin('AMap.Geocoder', () => {
					const geocoder = new AMap.Geocoder({
						radius: 100,
						extensions: 'all'
					})

					geocoder.getAddress(this.lnglat, (status, res) => {
						if (status === 'complete' && res.info === 'OK') {
							this.adr = res.regeocode

							this.callback()
						} else {
							console.log('fail,,,', status, res)
						}
					})
				})
			},

			// 回调
			callback() {
				const { addressComponent, formattedAddress } = this.adr

				this.$emit('callback', {
					province: addressComponent.province,
					city: addressComponent.city,
					district: addressComponent.district,
					township: addressComponent.township,
					address: formattedAddress,
					adcode: addressComponent.adcode,
					lnglat: this.lnglat
				})
			}
		}
	}
</script>

<style scoped>
	#container {
		overflow: hidden;
		width: calc(100% - 440px);
		height: 700px;
		margin: 0;
	}
</style>
